import { FunctionComponent, useState, useMemo, useEffect } from "react"
import Style from "./index.less"
import { Dialog, Popup, Stepper } from "antd-mobile"
import { ISell, IStore } from "../.."
import { formatPrice } from "@/utils"

export interface IShopCartProps {
    store?: Partial<IStore>;
    data?: ISell;
    onChange?: (d: ISell) => void;
}


const ShopCart: FunctionComponent<IShopCartProps> = (props) => {

    const { store, data, onChange } = props;
    const [visible, setVisible] = useState<boolean>(false)

    const totalPrice = useMemo(() => {
        if (!data) return 0;
        const p: number = data.reduce((total, curr) => {
            return total + curr.foods.reduce((t, c) => t + c.nums * c.price, 0)
        }, 0)
        return formatPrice(p)
    }, [data])


    const totalNums = useMemo(() => {
        if (!data) return 0;
        const n: number = data.reduce((total, curr) => {
            return total + curr.foods.reduce((t, c) => t + c.nums, 0)
        }, 0)
        return n
    }, [data])

    const updateShopcar = (o_index: number, i_index: number, value: number) => {
        const _data: ISell = JSON.parse(JSON.stringify(data));
        _data[o_index].foods[i_index].nums = value;
        onChange?.(_data)
    }

    useEffect(() => {
        if (totalNums === 0) setVisible(false)
    }, [data])

    const clear = () => {
        if (!data) return;
        onChange?.(data?.map(item => {
            item.foods = item.foods.map(itemize => ({ ...itemize, nums: 0 }))
            return item
        }))
    }

    const cost = () => {
        if(totalPrice<=0) return;
        Dialog.show({
            title:"提示",
            content: `您需要支付${totalPrice}元`,
            closeOnAction: true,
            actions: [
                [
                    {
                        key: 'cancel',
                        text: '取消',
                        danger: true
                    },
                    {
                        key: 'confirm',
                        text: '确定'
                    },
                ],
            ],
            onAction: (_e, i) => {
                if (i === 1) {
                    clear()
                }
            }
        })
    }

    return (
        <div className={Style.shopcart}>
            <div className={Style.shopcart_content} onClick={() => setVisible(!visible)}>
                <div className={Style.shopcart_content_left}>
                    <div className={`${Style.shopcart_content_icon} ${totalNums > 0 ? Style.active : ''}`}></div>
                    {
                        totalNums ? <div className={Style.badge}>{totalNums}</div> : null
                    }
                </div>
                <div className={`${Style.shopcart_content_price} ${totalPrice > 0 ? Style.active : ''}`}>￥{totalPrice}</div>
                <div className={Style.shopcart_content_delivery}>另需配送费￥{formatPrice(store?.deliveryPrice || 0)}元</div>
            </div>
            <div onClick={() => cost()} className={`${Style.shopcart_btn} ${totalPrice >= formatPrice(store?.minPrice || 1000) ? Style.active : ''}`}>{(() => {
                const minPrice = formatPrice(store?.minPrice || 0)
                if (totalPrice >= minPrice) return "去结算";
                else if (totalPrice == 0) return `￥${minPrice}元起送`
                else return `还差￥${formatPrice(minPrice - totalPrice)}元起送`
            })()}</div>
            <Popup
                className='adm_popup_custom'
                visible={visible}
                onMaskClick={() => setVisible(false)}
                onClose={() => {
                    setVisible(false)
                }}
            >
                <div className='shopcart_mask'>
                    <div className='shopcart_mask_title'>
                        <span>购物车</span>
                        <p onClick={() => clear()}>清空</p>
                    </div>
                    <div className="shopcart_mask_wrapper">
                        {
                            data?.map((item, index) => {

                                return (
                                    <div key={`select_${index}`}>
                                        {item.foods.map((itemize, g_index) => (
                                            itemize.nums ? <div key={`select_food_${index}_${g_index}`} className="shopcart_mask_line">
                                                <span>{itemize.name}</span>
                                                <div className="right">
                                                    <div className="right_price">￥{itemize.price * itemize.nums}</div>
                                                    <Stepper
                                                        value={itemize.nums}
                                                        onChange={value => {
                                                            updateShopcar(index, g_index, value)
                                                        }}
                                                    />
                                                </div>
                                            </div> : null
                                        ))}
                                    </div>
                                )
                            })
                        }
                    </div>
                </div>
            </Popup>
        </div>
    )
}

export default ShopCart